package com.media.publish.utils;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.liaoinstan.springview.utils.DensityUtil;
import com.media.R;
import com.media.publish.CoverSelectActivity;
import com.qiniu.pili.droid.shortvideo.PLMediaFile;

import com.media.publish.adapter.VideoCoversAdapter;

/**
 * 剪辑模块缩略图显示控件
 */
public class VideoCoversListView extends RelativeLayout implements ChoiceCoverSeek.OnScrollBorderListener {

    private Context mContext;
    private RecyclerView mRecyclerView;
    private VideoCoversAdapter mVideoFrameAdapter;
    private long mVideoDuration;
    private long mVideoStartTime;
    private long mVideoEndTime;
    private int mAllThumbnailWidth;
    private ChoiceCoverSeek mChoiceCover;
    private OnVideoCoverChangedListener mOnVideoRangeChangedListener;
    private MediaMetadataRetriever mMmr;
    private long lastTime;
    private long mEveryWidth;
    private float mStart;
    private Bitmap mCoversBitmap;
    private String mSDCardVideoPath;
    private static final String TAG = "VideoCoversListView";

    @Override
    public void OnScrollBorder(float start, float end) {
        long ViewWidth = mChoiceCover.getWidth();
        mEveryWidth = mVideoDuration / ViewWidth;
        mStart = start;
        if (mOnVideoRangeChangedListener != null) {
            if (lastTime == 0 || (lastTime != (long) (start * mEveryWidth * 1000))) {
                lastTime = (long) (start * mEveryWidth * 1000);
                mOnVideoRangeChangedListener.onVideoCoverChanged((long) (start * mEveryWidth * 1000));
            }
        }
    }

    @Override
    public void onScrollStateChange() {
        new Thread(() -> {
            Bitmap mBitmap = getVideoThumb(mSDCardVideoPath, (long) (mStart * mEveryWidth * 1000));
            if (mBitmap != null) {
                try {
                    ((CoverSelectActivity)mContext).runOnUiThread(() -> mChoiceCover.setBitmap(mBitmap));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mCoversBitmap = mBitmap;
            }
        }).start();
    }

    public Bitmap getCoversBitmap() {
        return mCoversBitmap;
    }

    public interface OnVideoCoverChangedListener {
        void onVideoCoverChanged(long times);
    }

    public VideoCoversListView(Context context) {
        super(context);
    }

    public VideoCoversListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public VideoCoversListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void init(Context context, String sDCardVideoPath, PLMediaFile mediaFile, int frameCount) {
        mContext = context;
        mSDCardVideoPath = sDCardVideoPath;
        mMmr = new MediaMetadataRetriever();
        mMmr.setDataSource(sDCardVideoPath);
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.view_covers_trim, this, true);


        mRecyclerView = findViewById(R.id.recycler_view);
        mChoiceCover = findViewById(R.id.choice_cover);
        findViewById(R.id.range_slider).setVisibility(GONE);
        mChoiceCover.setVisibility(VISIBLE);
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecyclerView.setLayoutManager(manager);

        mVideoFrameAdapter = new VideoCoversAdapter(getContext());
        mRecyclerView.setAdapter(mVideoFrameAdapter);

        mVideoDuration = mediaFile.getDurationMs();
        mVideoStartTime = 0;
        mVideoEndTime = mVideoDuration;

        setLayoutParams();

        mVideoFrameAdapter.setFrameWidth(mAllThumbnailWidth / (frameCount + 1));
        mChoiceCover.setMinInterval(mAllThumbnailWidth / (frameCount + 2), mVideoDuration);
        mChoiceCover.setOnScrollBorderListener(this);
    }

    public void setOnVideoRangeChangedListener(OnVideoCoverChangedListener listener) {
        mOnVideoRangeChangedListener = listener;
    }

    public void addBitmap(Bitmap bitmap) {
        mVideoFrameAdapter.add(bitmap);
    }

    public long getVideoStartTime() {
        return mVideoStartTime;
    }

    public long getVideoEndTime() {
        return mVideoEndTime;
    }

    private void setLayoutParams() {
        ViewGroup.LayoutParams layoutParams = getLayoutParams();
        Resources resources = getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        int screenWidth = dm.widthPixels;
//        layoutParams.width = screenWidth - 2 * resources.getDimensionPixelOffset(R.dimen);
        layoutParams.width = screenWidth - 2 * DensityUtil.dip2px(getContext(), 10);
        setLayoutParams(layoutParams);
        mAllThumbnailWidth = layoutParams.width;
    }

    /**
     * 获取视频文件截图
     *
     * @param path 视频文件的路径
     * @return Bitmap 返回获取的Bitmap
     */
    public Bitmap getVideoThumb(String path, long times) {
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(path);
        Bitmap frameAtTime = media.getFrameAtTime(times, MediaMetadataRetriever.OPTION_CLOSEST);//getFrameAtTime 以微妙获取的帧
        media.release();
        return frameAtTime;
    }

    public void onDestroy() {
        if (mMmr != null) {
//            mMmr.release();
        }
    }
}
